#!/usr/bin/env python
#
#   Copyright (C) 2006 by Patrick Stinson                                 
#   patrickkidd@gmail.com                                                   
#                                                                         
#   This program is free software; you can redistribute it and/or modify  
#   it under the terms of the GNU General Public License as published by  
#   the Free Software Foundation; either version 2 of the License, or     
#   (at your option) any later version.                                   
#                                                                         
#   This program is distributed in the hope that it will be useful,       
#   but WITHOUT ANY WARRANTY; without even the implied warranty of        
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         
#   GNU General Public License for more details.                          
#                                                                         
#   You should have received a copy of the GNU General Public License     
#   along with this program; if not, write to the                         
#   Free Software Foundation, Inc.,                                       
#   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  
#

import sys
import time
import socket
import threading
import scosc
from scosc import OSC


class OSCEcho(threading.Thread):

    _timeout = .1
    
    def __init__(self, port):
        threading.Thread.__init__(self)        
        self._running = False
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(('', port))
        self.socket.settimeout(self._timeout)

    def quit(self):
        self._running = False

    def run(self):
        self._running = True
        try:
            while self._running:
                try:
                    data, address = self.socket.recvfrom(2**12)
                    print address
                    OSC.hexDump(data)
                    print scosc.decode(data)
                except socket.timeout:
                    pass
        except KeyboardInterrupt, e:
            pass


def main():
    import sys
    print """This dumps the hex and ascii of OSC messages like SuperCollider"""

    if '-h' in sys.argv:
        help = """ Usage: %s [port] """ % sys.argv[0]
        sys.exit()
    
    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 57110

    echoosc = OSCEcho(port)
    echoosc.start()
    print 'Hit enter to exit'
    sys.stdin.read(1)
    echoosc.quit()
    echoosc.join()
    
if __name__ == '__main__':
   main()
